package com.sugon.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.sugon.annotation.DataFilter;
import com.sugon.consts.ErmsCodePrefix;
import com.sugon.dao.ModuleArchivesDao;
import com.sugon.dao.ModuleTypeDao;
import com.sugon.entity.ModuleArchivesEntity;
import com.sugon.entity.ModuleTypeEntity;
import com.sugon.entity.SysDeptEntity;
import com.sugon.modules.sys.consts.SysDeptConst;
import com.sugon.service.ModuleArchivesService;
import com.sugon.service.ModuleChangeLogService;
import com.sugon.service.SysDeptService;
import com.sugon.utils.ShiroUtils;
import com.sugon.utils.StringUtils;
import com.sugon.utils.excel.ExcelImport;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 模具档案信息Service实现类
 *
 * @author sugon
 * @date 2019-08-06 16:33:04
 */
@Service("moduleArchivesService")
public class ModuleArchivesServiceImpl implements ModuleArchivesService {
    @Autowired
    private ModuleArchivesDao moduleArchivesDao;
    @Autowired
    private ModuleChangeLogService moduleChangeLogService;
    @Autowired
    private ModuleTypeDao moduleTypeDao;
    @Autowired
    private SysDeptService deptService;

    @Override
    public ModuleArchivesEntity queryObjectByCode(String code) {
        return moduleArchivesDao.queryObjectByCode(code);
    }

    @Override
    public int countByLastCode(String id, String lastCode) {
        Map<String, Object> param = MapUtil.newHashMap(1);
        param.put("lastCode", lastCode);
        if (StrUtil.isNotEmpty(id)) {
            param.put("id", id);
        }
        return moduleArchivesDao.queryTotal(param);
    }

    @Override
    public ModuleArchivesEntity queryObjectByNo(String moduleNo) {
        Map<String, Object> param = MapUtil.newHashMap(1);
        param.put("moduleNo", moduleNo);
        List<ModuleArchivesEntity> moduleArchivesList = queryList(param);
        return CollectionUtil.isNotEmpty(moduleArchivesList) ? moduleArchivesList.get(0) : null;
    }

    @Override
    public ModuleArchivesEntity queryObject(String id) {
        return moduleArchivesDao.queryObject(id);
    }

    @Override
    public List<ModuleArchivesEntity> queryList(Map<String, Object> map) {
        return moduleArchivesDao.queryList(map);
    }

    @Override
    public List<ModuleArchivesEntity> queryList(String moduleType) {
        Map<String, Object> param = MapUtil.newHashMap();
        if (StrUtil.isNotEmpty(moduleType)) {
            param.put("moduleType", moduleType);
        }
        return queryList(param);
    }

    @Override
    public List<ModuleArchivesEntity> queryListTicketMold(Map<String, Object> map) {
        return moduleArchivesDao.queryListTicketMold(map);
    }

    @Override
    public int queryTotalTicketMold(Map<String, Object> map) {
        return moduleArchivesDao.queryTotalTicketMold(map);
    }

    @Override
    public List<ModuleArchivesEntity> queryListApi(Map<String, Object> map) {

        return moduleArchivesDao.queryList(map);
    }

    @Override
    @DataFilter(userAlias = "", deptAlias = "SUB_SHOP")
    public int queryTotal(Map<String, Object> map) {
        String userDeptId = MapUtil.getStr(map, "deptId");
        if (StrUtil.isEmpty(userDeptId)) {
            userDeptId = ShiroUtils.getDeptId();
        }
        if (StrUtil.isNotEmpty(userDeptId)) {
            if (!userDeptId.startsWith(SysDeptConst.ZZC_CODE) && userDeptId.length() > 3) {
                map.put("subShop", userDeptId.substring(0, 4));
            }
        }
        return moduleArchivesDao.queryTotal(map);
    }

    @Override
    public int save(ModuleArchivesEntity moduleArchives) {
        moduleArchives.setId(RandomUtil.randomString(32));
        moduleArchives.setModuleCode(generateUniqueCode(moduleArchives));
        moduleArchives.setDelFlag(1);
        moduleArchives.setCreateUser(ShiroUtils.getUserId());
        moduleArchives.setCreateDate(DateUtil.date());
        return moduleArchivesDao.save(moduleArchives);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int update(ModuleArchivesEntity moduleArchives) {
        moduleArchives.setUpdateUser(ShiroUtils.getUserId());
        moduleArchives.setUpdateDate(new Date());
        // 如果部门不一致，需要生成模具变动记录信息
        ModuleArchivesEntity old = this.queryObject(moduleArchives.getId());
        if (old != null) {
            // 原所属车间
            String subCode = old.getSubShop();
            // 当前车间
            String nowCode = moduleArchives.getSubShop();
            if (StrUtil.isAllNotEmpty(subCode, nowCode)) {
                //两次部门不一致，记录变更日志
                if (!subCode.equals(nowCode)) {
                    moduleChangeLogService.save(subCode, nowCode, old.getModuleCode(), old.getModuleNo());
                }
            }
        }
        // 更新模具信息
        return moduleArchivesDao.update(moduleArchives);
    }

    @Override
    public int delete(String id) {
        return moduleArchivesDao.delete(id);
    }

    @Override
    public int deleteBatch(String[] ids) {
        return moduleArchivesDao.deleteBatch(ids);
    }

    @Override
    public String generateUniqueCode(Object object) {

        ModuleArchivesEntity moduleArchives = (ModuleArchivesEntity) object;
        // 获取模具唯一码前缀：固定的CQE- + 产品类型组成
        String moldUniqueCodePrefix = ErmsCodePrefix.MODULE_CODE_PREFIX;
        if (StrUtil.isNotEmpty(moduleArchives.getModuleSeries())) {
            moldUniqueCodePrefix += moduleArchives.getModuleSeries() + "-";
        }
        int num = 1;
        String lastestModuleCode = moduleArchivesDao.getLastestModuleCode(moldUniqueCodePrefix);
        if (StrUtil.isNotEmpty(lastestModuleCode)) {
            num += Integer.parseInt(lastestModuleCode.replace(moldUniqueCodePrefix, ""));
        }
        return moldUniqueCodePrefix + String.format("%05d", num);
    }

    /**
     * 数据导入
     *
     * @param file
     * @return
     */
    @Override
    public int importE(MultipartFile file) {
        //获取所有表格数据
        List<String[]> list = ExcelImport.getExcelData(file);
        int count = 0;
        if (CollectionUtil.isNotEmpty(list)) {
            for (int i = 1; i < list.size(); i++) {
                ModuleArchivesEntity mae = new ModuleArchivesEntity();
                mae.setId(RandomUtil.randomString(32));
                mae.setCreateDate(new Date());
                mae.setCreateUser(ShiroUtils.getUserId());
                mae.setDelFlag(1);
                String[] array1 = list.get(i);
                // 如果模具号都为空，那么说明无效数据，不读取
                if (StrUtil.isEmpty(array1[2]) || array1[2].trim().length() == 0) {
                    continue;
                }
                String[] array = new String[10];
                System.arraycopy(array1, 0, array, 0, array1.length);
                //模具编码
                mae.setModuleCode(generateUniqueCode());
                //模具类型
                if (StringUtils.isNotEmpty(array[1])) {
                    String code = array[1];
                    ModuleTypeEntity type = moduleTypeDao.queryObjectByCode(code);
                    if (type != null) {
                        mae.setModuleType(type.getId());
                        mae.setModuleTypeName(type.getTypeName());
                    }
                }
                //模具编号
                if (StringUtils.isNotEmpty(array[2])) {
                    String sno = array[2];
                    mae.setModuleNo(sno);
                }
                //模具机型
                if (StringUtils.isNotEmpty(array[3])) {
                    String productModel = array[3];
                    mae.setProductModel(productModel);
                }
                //寿命标准
                if (StringUtils.isNotEmpty(array[4])) {
                    String standard = array[4];
                    mae.setLifeStandard(Integer.parseInt(standard));
                    mae.setRemainNo(Integer.parseInt(standard));
                    mae.setUseNo(0);
                }
                //所在车间(系统架构编码)
                if (StringUtils.isNotEmpty(array[5])) {
                    String dept = array[5];
                    if (StrUtil.isNotEmpty(dept)) {
                        SysDeptEntity sysDept = deptService.getByDCode(dept);
                        if (sysDept != null) {
                            mae.setSubShop(sysDept.getDeptId());
                        }
                    }
                }
                //启用时间
                if (StringUtils.isNotEmpty(array[6])) {
                    String date = array[6];
                    Date startDate = DateUtil.parseDate(date);
                    mae.setStartDate(startDate);
                }
                //当前状态（1: '在用', 2: '备用', 3: '试模', 4: '维护', 5: '维修', 6: '封存'）
                if (StringUtils.isNotEmpty(array[7])) {
                    int status = Integer.parseInt(array[7]);
                    mae.setCurrentState(status);
                }
                //模具类别
                if (StringUtils.isNotEmpty(array[8])) {
                    //mae.setModuleCategory(array[8]);
                }
                //固资编号
                if (StringUtils.isNotEmpty(array[9])) {
                    mae.setFirmCapitalNo(array[9]);
                }
                if (moduleArchivesDao.save(mae) > 0) {
                    count++;
                }
            }
        }
        return count;
    }
}
